import React from 'react';
import { browserHistory, Link } from 'react-router';
import { Form, Icon, Input, Button, Checkbox, InputNumber, Radio, Spin, Collapse, Upload, message, Modal, Row, Col } from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Panel = Collapse.Panel;
const TextArea = Input.TextArea;
import * as actions from './../../actions/frontEnd/loginAction';

class myProfile extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        loading: false,
        tipUpdate: "修改信息，请稍候...",
        myProfile: {}
    }
  }
  componentDidMount(){
    if(sessionStorage.getItem("username") != null){
      actions.findProfileById(this);
    }
    window.onresize = function () {
      var clientHeight = document.body.clientHeight - 30;
      $(".loginForm").css("height",clientHeight + "px");
    }
    window.onresize();
  }
  goBackHome (){
    browserHistory.push("/index");
  }
  handleSubmit = (e) => {
    e.preventDefault(); var that = this;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.id = that.state.myProfile.id;
        values.uId = that.state.myProfile.uId;
        values.scIds = that.state.myProfile.scIds;
        values.followProductIds = that.state.myProfile.followProductIds;
        if(that.state.myProfile.photoPic != undefined && that.state.myProfile.photoPic != ""){
          values.photoPic = that.state.myProfile.photoPic;
        }
        actions.updateProfile(this, values);
      }
    });
  }
  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  beforeUpload(file) {
    const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp');
    if (!isJPG) {
      message.error('你能上传 JPG, PNG, GIF 或 BMP 文件!');
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于 2MB!');
      return false
    }
    return isJPG && isLt2M;
  }
  uploadChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true, tipUpdate: "上传头像..." });
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
      Modal.success({
        title: '提示：',
        content: '头像 上传成功！'
      });
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传头像</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    const headers = {userAuth: sessionStorage.getItem('userAuth')}
    return (
      <div className="loginForm">
          <div className="divBackground"></div>
          <Spin spinning={this.state.loading} tip={this.state.tipUpdate}>
            <Form onSubmit={this.handleSubmit} className="login-form" style={{maxWidth: '472px'}}>
              <div className="divSex">
                <div className="divAvatarLabel">头像</div>
                <Upload
                  name="myPhoto"
                  headers={headers}
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="http://192.168.0.51:8881/webAPI/setting/changePortrait"
                  beforeUpload={this.beforeUpload}
                  onChange={this.uploadChange}
                  className="uploadAvatar"
                >
                  {imageUrl ? <img src={imageUrl} style={{height: '86px'}}/> : uploadButton}
                </Upload>
              </div>
              <FormItem>
                {getFieldDecorator('firstName', {
                  rules: [{ required: true, message: '请输入 姓氏。' }],
                  initialValue: this.state.myProfile.firstName
                })(
                  <Input addonBefore={<div style={{width: '67px'}}>姓氏</div>} placeholder="姓氏" size="large" />
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('lastName', {
                  rules: [{ required: true, message: '请输入 名称。' }],
                  initialValue: this.state.myProfile.lastName
                })(
                  <Input addonBefore={<div style={{width: '67px'}}>名字</div>} placeholder="名称" size="large" />
                )}
              </FormItem>
              <div className="divSex">
                <div className="divSexLabel">性别</div>
                <FormItem>
                  {getFieldDecorator('gender', {
                    rules: [{ required: true, message: '请选择 性别。' }],
                    initialValue: this.state.myProfile.gender
                  })(
                      <RadioGroup style={{marginLeft: '10px'}}>
                        <Radio value="1">男</Radio>
                        <Radio value="2">女</Radio>
                      </RadioGroup>
                  )}
                </FormItem>
              </div>
              <div className="divSex">
                <div className="divSexLabel">年龄</div>
                <FormItem>
                  {getFieldDecorator('age', {
                    rules: [{ required: false}],
                    initialValue: this.state.myProfile.age
                  })(
                      <InputNumber min={1} max={120} style={{marginLeft: '10px'}}/>
                  )}
                </FormItem>
              </div>
              <FormItem>
                {getFieldDecorator('job', {
                  rules: [{ required: false}],
                  initialValue: this.state.myProfile.job
                })(
                  <Input addonBefore={<div style={{ width: '67px'}}>工作</div>} placeholder="job" size="large"/>
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('location', {
                  rules: [{ required: true, message: '请输入国家城市。' }],
                  initialValue: this.state.myProfile.location
                })(
                  <Input addonBefore={<div style={{width: '67px'}}>国家城市</div>} placeholder="国家 / 城市" size="large"/>
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('position', {
                  rules: [{ required: true, message: '请输入 家庭地址。' }],
                  initialValue: this.state.myProfile.position
                })(
                  <Input addonBefore={<div style={{width: '67px'}}>家庭地址</div>} placeholder="街道地址" size="large"/>
                )}
              </FormItem>
              <div>
                <div>个人简介：</div>
                <FormItem>
                  {getFieldDecorator('overview', {
                    rules: [{ required: false}],
                    initialValue: this.state.myProfile.overview
                  })(
                      <TextArea placeholder="个人简介" rows={4} />
                  )}
                </FormItem>
              </div>
              <Collapse bordered={false} className="collapseBordered">
                <Panel header="电话 & 邮箱 信息" key="1">
                  <FormItem>
                    {getFieldDecorator('phoneNum', {
                      // rules: [{ required: true, message: 'Please input your phoneNum.' }],
                      initialValue: this.state.myProfile.phoneNum
                    })(
                      <Input addonBefore={<div style={{width: '67px'}}>电话</div>} placeholder="手机号码" size="large" disabled={true}/>
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('email', {
                      rules: [{ required: true, message: '请输入 电子邮箱。' }],
                      initialValue: this.state.myProfile.email
                    })(
                      <Input addonBefore={<div style={{width: '67px'}}>邮箱</div>} placeholder="电子邮箱" size="large" disabled={true}/>
                    )}
                  </FormItem>
                </Panel>
              </Collapse>
              <FormItem>
                <Row>
                  <Col span={24} style={{ textAlign: 'right', display: 'flex' }}>
                    <Button type="danger" className="login-back-button" onClick={this.goBackHome}>主 页</Button>
                    <Button type="primary" htmlType="submit" className="login-form-button">修改个人信息</Button>
                  </Col>
                </Row>
              </FormItem>
            </Form>
          </Spin>
      </div>
    );
  }
}
const myProfileForm = Form.create()(myProfile);
export default myProfileForm;
